﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace KZ.CustomControl
{
    public class MultiColumnComboBox : ComboBox
    {
        private object _source; //// store data source of combobox
        private int _dropDownWidth;
        private Dictionary<string, string> _displayColumns; //// store column definition, key is column name, value is header text
        private MultiColumnDropDown _dropDown;

        protected override void OnDropDown(EventArgs e)
        {
            if (Source != null)
                //// only show dropdown if datasource is not null
                ShowDropDown();
        }

        protected override void OnSelectedValueChanged(EventArgs e)
        {
            base.OnSelectedValueChanged(e);
        }

        private void dropDown_AfterRowSelectEvent(object sender, object value)
        {
            base.SelectedValue = value;
        }

        private void ShowDropDown()
        {
            Control parent = base.Parent;
            Point point = parent.PointToScreen(base.Location);

            if (_dropDown == null)
            {
                _dropDown = new MultiColumnDropDown();
                _dropDown.Width = _dropDownWidth == 0 ? base.Width : _dropDownWidth; //// set dropdownwidth
                _dropDown.DisplayColumns = _displayColumns; //// set datagridview columns
                _dropDown.DisplayMember = base.DisplayMember;
                _dropDown.ValueMember = base.ValueMember;
                _dropDown.AfterRowSelectEvent += dropDown_AfterRowSelectEvent;
            }
            _dropDown.Source = _source; //// set datasource
            _dropDown.Location = new Point(point.X, point.Y + base.Height); //// set location
            _dropDown.Show();
        }

        public MultiColumnComboBox()
            : base()
        {
            _displayColumns = new Dictionary<string, string>();
            base.DropDownHeight = 1;
        }

        /// <summary>
        /// DataSource
        /// </summary>
        public object Source
        {
            get { return _source; }
            set
            {
                _source = value;
                base.DataSource = value;
            }
        }

        public new int DropDownWidth
        {
            get { return _dropDownWidth; }
            set { _dropDownWidth = value; }
        }

        public Dictionary<string, string> DisplayColumns
        {
            get { return _displayColumns; }
            set { _displayColumns = value; }
        }
    }
}